package org.hyacinth.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.hyacinth.common.pojo.Result;
import org.hyacinth.common.utils.JWTUtils;
import org.hyacinth.gateway.config.WhiteProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Resource
    private ObjectMapper objectMapper;

    //private List<String> whiteNames = List.of("/user/login", "/user/register");
    @Resource
    private WhiteProperties whiteProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 配置白名单
        ServerHttpRequest request = exchange.getRequest();

        String path = request.getURI().getPath();
        List<String> url = whiteProperties.getUrl();
        if (url != null && url.contains(path)) {
            // 放行
            return chain.filter(exchange);
        }

        String userToken = request.getHeaders().getFirst("user_token");
        if (!StringUtils.hasText(userToken)) {
            return unauthorizedResp(exchange, "令牌为空！");
        }
        Claims claims = JWTUtils.parseJWT(userToken);
        if (claims == null) {
            return unauthorizedResp(exchange, "令牌校验失败！");
        }
        return chain.filter(exchange);
    }

    @SneakyThrows
    private Mono<Void> unauthorizedResp(ServerWebExchange exchange, String errMsg) {
        ServerHttpRequest request = exchange.getRequest();
        log.error("用户身份认证失败:url = " + request.getURI().getPath());
        // 设置响应状态码 响应格式
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        Result result = Result.fail(errMsg);
        DataBuffer dataBuffer = response.bufferFactory().wrap(objectMapper.writeValueAsBytes(result));
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
